<?php

namespace app\admin\controller;

use app\lib\exception\ParameterException;
use app\common\BaseHelper;
use app\common\Common;

use app\admin\model\Member as MemberMdl;
use app\admin\model\Memberextrainfo;
use app\admin\model\Memberresume;
use app\admin\model\Organization;
use app\admin\model\Institution;
use app\admin\model\Department;
use app\admin\model\Ethnic;
use app\admin\model\Image;
use app\admin\model\Povertymember;
use app\admin\model\Villages;
use app\admin\model\Area;
use app\admin\service\Member as MemberService;

use think\Db;
use think\Exception;
use think\Request;

class Member extends Base
{

    protected $isIframe = false;

    public function _initialize()
    {

        $this->accessAction = ['index', 'add', 'shenhe'];
        $this->exceptAction = ['checkIdentityNumber'];

        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['isDelete'] = ['neq', 1];
        //$defaultWhere['shenheStatus'] = ['<', 2];  //过滤掉审核失败或审核中状态的数据
        $this->defaultWhere = $defaultWhere;

        $this->searchFields = [
            'name' => [
                'label'     => '姓名',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
            'identityNumber' => [
                'label'     => '身份证',
                'field'     => 'identityNumber',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];

        $type = $this->request->param('type');
        $this->assign('type', $type);

        if($this->request->action() == 'add' || $this->request->action() == 'edit'){
            // 与户主关系
            $relatedHouseholderList = get_relatedHouseholder();
            // 名族
            $ethnics = Ethnic::order('sorting ASC')->select();
            $ethnicList = collection($ethnics)->toArray();
            // 文化程度
            $educationList = get_education();

            $this->assign('relatedHouseholderList', $relatedHouseholderList);
            $this->assign('ethnicList', $ethnicList);
            $this->assign('educationList', $educationList);
        }
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($where, $this->defaultWhere);
            }
            /*if($this->defaultOrder){
                $model = $model->order($this->defaultOrder);
            }*/

            $whereStr = "checkParty = 1 OR checkInstitution = 1 OR checkVillager = 1 OR checkPoverty = 1";
            if($param['columns'][$columns]['data'] == 'name'){
                $order = 'CONVERT(name USING gbk)' . $param['order'][0]['dir'];
                $list = $model->where($where)->where($whereStr)->limit($start, $length)->order($order)->select();
            }else{
                $list = $model->where($where)->where($whereStr)->limit($start, $length)->order($order)->select();
            }
            if ($list) {
                foreach ($list as $item) {
                    // 所在地
                    $item['area'] = getArea($item);
                }
            }
            $count = $model->where($where)->where($whereStr)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Add Post
     */
    public function addPost(Request $request, $redirect = ''){
        $model = model($this->model);
        if ($request->isPost()) {
            $request->post(['shenheStatus' => 0]);

            $data = $request->param();
            $identityNumber = $data['identityNumber'];
            $info = $model->where(['identityNumber' => $identityNumber])->find();

            Db::startTrans();
            try {
                if($info){
                    // 将已删除的村民 进行更新
                    $data['id'] = $info['id'];
                    $data['createDate'] = time();
                    $data['createOper'] = $this->admin->id;
                    $data['isDelete'] = 2;
                    // 添加User表数据，与Member表关联
                    $data['userId'] = $this->addUser($data['id']);

                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                }else{
                    // Insert data
                    $data['id'] = BaseHelper::getUUID();
                    $data['createDate'] = time();
                    $data['createOper'] = $this->admin->id;
                    // 添加User表数据，与Member表关联
                    $data['userId'] = $this->addUser($data['id']);

                    $result = $model->save($data);
                }

                if($result !== false) {
                    // 保存额外属性信息
                    $res = $this->saveExtrainfo($data);

                    if($res['code'] != 1){
                        Db::rollback();
                        return $this->error($res['msg']);
                    }

                    // Query执行后的操作
                    $model->_after_insert($data);

                    // 写入日志
                    $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('添加成功！', 'admin/' . strtolower($this->model) . '/index');
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('请求方式错误！');
        }
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        /*$join = [
            ['__MEMBEREXTRAINFO__ e', 'e.memberId = a.id']
        ];
        $fields = 'a.*, e.*';
        $info = $model->alias('a')->join($join)->field($fields)->find($id);*/
        $info = $model->find($id);
        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        $areaMdl = new Area();
        $city = BaseHelper::makeOptions(
            $areaMdl,
            ['level' => 1],
            ['id' => 'asc']
        );
        $this->assign('city', $city);

        // 额外属性信息
        $extrainfo = Memberextrainfo::where(['memberId' => $info['id']])->find();
        if($extrainfo['householderId']){
            $extrainfo['householderName'] = $model->where('id', $extrainfo['householderId'])->value('name');
        }

        $this->assign('extrainfo', $extrainfo);

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Edit Post
     */
    public function editPost(Request $request, $redirect = ''){
        $model = model($this->model);
        if ($request->isPost()) {
            $data = $request->param();

            Db::startTrans();
            try {
                // 删除已删除的村民
                $identityNumber = $data['identityNumber'];
                $model->where(['identityNumber' => $identityNumber, 'isDelete' => 1])->delete();

                $data['updateDate'] = time();
                $data['updateOper'] = $this->admin->id;
                // 添加User表数据，与Member表关联
                $data['userId'] = $this->addUser($data['id']);

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                if($result !== false) {
                    // 保存额外属性信息
                    $res = $this->saveExtrainfo($data);
                    if($res['code'] != 1){
                        Db::rollback();
                        return $this->error($res['msg']);
                    }

                    // Query执行后的操作
                    $model->_after_update($data);

                    // 写入日志
                    $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('编辑失败！');
        }
    }

    /**
     * 保存额外属性信息
     */
    public function saveExtrainfo($params){
        $result = MemberService::saveExtrainfo($params);

        return $result;
    }

    /**
     * 添加User表数据（与Member表关联）
     */
    protected function addUser($memberId){
        $userId = model('Member')->where(['id' => $memberId])->value('userId');
        if($userId){
            return $userId;
        }

        $data = [
            'id' => BaseHelper::getUUID22(),
            'memberId' => $memberId
        ];
        $result = \app\admin\model\User::insert($data);

        return $data['id'];
    }

    /**
     * Delete
     */
    public function delete(){
        $model = model($this->model);
        $request = $this->request;
        $id = $request->param('id');

        $member = $model->where('id',$id)->find();

        // 判断是否为管理员
        $operator = \app\admin\model\Operator::where(['memberId' => $id, 'isDelete' => 2])->find();
        if($operator) {
            return $this->error('该村民是管理员，请先去删除管理员');
        }

        // TODO 有扶贫项目和扶贫工作 是否还能删除
        /*$projectWhere = "(memberId = {$id}) OR (aidingId = {$id})";
        $project = db('povertyproject')->where($projectWhere)->find();
        if($project){
            return $this->error('该村民有扶贫项目，请先去删除有扶贫项目');
        }*/

        $data = [
            'isDelete' => 1,
            'userId' => '',
            'shenheStatus' => 2,
        ];
        $result = $model->where('id', $id)->update($data);
        $userInfo = \app\admin\model\User::where('memberId', $id)->find();
        if($userInfo){
            $userInfo->memberId = Null;
            $userInfo->save();
        }
        if($result !== false){
            Povertymember::where(['aidingId' => $id])->update(['aidingId' => '']); // 将帮扶人为该村民的帮扶人去除

            // 是否是贫困户
            if($member['isPoverty'] == 1) {
                // 删除povertymember表相关数据
                Povertymember::where(['memberId' => $id])->delete();
            }
            // 删除扶贫项目
            $projectWhere = "(memberId = {$id}) OR (aidingId = {$id})";
            db('povertyproject')->where($projectWhere)->update(['isDelete' => 1]);
            // 删除扶贫工作
            $workWhere = "(povertymemberId = {$id}) OR (povertypartyId = {$id})";
            db('povertywork')->where($workWhere)->update(['isDelete' => 1]);

            // Query执行后的操作
            $model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功！', 'admin/' . strtolower($request->controller()) . '/index');
        } else {
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

    /**
     * 检查身份证号是否已存在
     */
    public function checkIdentityNumber(){
        if($this->request->isAjax()){
            $identityNumber = $this->request->param('identityNumber');
            $model = model($this->model);

            $result = $model->where(['identityNumber' => $identityNumber, 'isDelete' => 2])->field('identityNumber')->find();

            if($result){
                return json(['status' => 1]);
            }else{
                return json(['status' => 0]);
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['memberType']) && $filter['memberType']){
                $where['memberType'] = $filter['memberType'];
            }
            if(isset($filter['memberType']) && $filter['memberType'] != 2){
                if(isset($filter['cityId']) && $filter['cityId']){
                    $where['cityId'] = $filter['cityId'];
                }
                if(isset($filter['xianId']) && $filter['xianId']){
                    $where['xianId'] = $filter['xianId'];
                }
                if(isset($filter['townId']) && $filter['townId']){
                    $where['townId'] = $filter['townId'];
                }
                if(isset($filter['villageId']) && $filter['villageId']){
                    $where['villageId'] = $filter['villageId'];
                }
            }

            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
            if(isset($filter['identityNumber']) && $filter['identityNumber']){
                $where['identityNumber'] = ['like', '%'.$filter['identityNumber'].'%'];
            }
        }

        return $where;
    }

    /**
     * 下载Excel模板
     */
    public function downloadTemplate(){
        MemberService::downloadTemplate($this->request);
    }

    /**
     * 导入数据
     */
    public function import(){
        $result = MemberService::import();

        return $result;
    }

    /**
     * 导出数据
     */
    public function export(){
        $result = MemberService::export($this->request);
        if($result['code'] == 2){
            $this->error($result['msg'], url('admin/member/index'));
        }

        return redirect('admin/member/index');
    }

}